/*******************************************************************************
 * Copyright (c) 2005-2008 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *     Brad Reynolds - bug 159539
 *     Brad Reynolds - bug 140644
 *     Brad Reynolds - bug 159940
 *     Brad Reynolds - bug 116920, 159768
 *     Matthew Hall - bug 118516
 *     Matthew Hall - bug 124684
 *     Tran Nhut Trung - Support GWT
 *******************************************************************************/
package org.eclipse.core.databinding;

import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.Widget;

import java.util.Iterator;

import org.eclipse.core.databinding.observable.gwt.IWidgetObservable;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;

public class GWTDataBindingContext extends DataBindingContext {
  private static final String VALIDATION_ERROR_STYLE_NAME = "validationError";
  
  public GWTDataBindingContext() {
  }

  protected UpdateValueStrategy createModelToTargetUpdateValueStrategy(
      IObservableValue fromValue, IObservableValue toValue) {
    return new GWTUpdateValueStrategy();
  }

  protected UpdateValueStrategy createTargetToModelUpdateValueStrategy(
      IObservableValue fromValue, IObservableValue toValue) {
    return new GWTUpdateValueStrategy();
  }
  
  /**
   * Utility method
   * @return
   */
  public IStatus getStatusMaxSeverity(){
    int maxSeverity = IStatus.OK;
    IStatus maxStatus = Status.OK_STATUS;

    for (Iterator it = this.getBindings().iterator(); it.hasNext();) {
      Binding binding = (Binding)it.next();
      IStatus status = (IStatus) binding
          .getValidationStatus().getValue();
      if (status.getSeverity() > maxSeverity) {
        maxSeverity = status.getSeverity();
        maxStatus = status;
      }
      
      UIObject widget = null;
      if (binding.getTarget() instanceof IWidgetObservable){
        widget = ((IWidgetObservable)binding.getTarget()).getWidget();
      }
      if (widget != null){
        if (!status.isOK()) {
          widget.addStyleName(VALIDATION_ERROR_STYLE_NAME);
          status.getException().printStackTrace();
        }else{
          widget.removeStyleName(VALIDATION_ERROR_STYLE_NAME);
        }
      }
    }
    return maxStatus;
  }
}
